//
//  OADetailViewController.m
//  OASystem
//
//  Created by zhoupengfei on 15/3/31.
//  Copyright (c) 2015年 zpf. All rights reserved.
//

#import "OADetailViewController.h"
#import "OADetailCell.h"
#import "HttpTools.h"
#import "GDataDefines.h"
#import "OADetailModel.h"
#import "OAToolBox.h"
#import "OAAttachmentsModel.h"
#import "MBProgressHUD.h"
#import "OAAttachmentsModel.h"
#import <QuickLook/QuickLook.h>
#import "OAHistroyViewController.h"
#import "OASelectDepartmentController.h"
#import "OADepartmentModel.h"
#import "UIAlertView+Blocks.h"
#import "Toast+UIView.h"
#import "OASelectPersonController.h"


@interface OADetailViewController ()<UIWebViewDelegate,QLPreviewControllerDataSource,QLPreviewControllerDelegate,UIAlertViewDelegate,UITextFieldDelegate>
@property(nonatomic,strong)  OADetailModel * detailModel ;
@property(nonatomic,strong)NSMutableArray * attachmentArray; //附件
@property(nonatomic,strong)NSMutableArray * mainattachmentArray; //正文附件
@property(nonatomic,strong)NSString * attacmentURL;
@property(nonatomic,assign)BOOL isEditoring; //编辑中
@property(nonatomic,strong)NSMutableArray * departments;

@property(nonatomic,copy)NSString * infoString; //服务器返回字段 根据该字段跳转不同的界面
@property(nonatomic,copy)NSString * textString ; //记录填写的意见
@property(nonatomic,copy)NSString   * body;
@property(nonatomic,strong)NSMutableArray * subItems; //选中 需要提交得数据
@end

@implementation OADetailViewController

-(NSMutableArray*)attachmentArray{
    if (_attachmentArray ==nil) {
        _attachmentArray = [NSMutableArray array];
    }
    return _attachmentArray;
}

-(NSMutableArray*)mainattachmentArray{
    if (_mainattachmentArray == nil) {
        _mainattachmentArray = [NSMutableArray array];
    }
    return _mainattachmentArray;
}

-(NSMutableArray*)subItems{
    if (_subItems ==nil) {
        _subItems = [NSMutableArray array];
    }
    return _subItems;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"详情";
    UIBarButtonItem * rightItem = [[UIBarButtonItem alloc]initWithTitle:@"流转历史" style:UIBarButtonItemStylePlain target:self action:@selector(historyAction)];
    self.navigationItem.rightBarButtonItem = rightItem;
    self.tableView.hidden = YES;
    //加载网络数据
    [self loadData];
    if (self.isAlreadDoneWork) {
        self.footView.hidden = YES;
       
    }else{
        if (self.isUnDoWork) {
            [self.operationBtn setTitle:@"签收" forState:UIControlStateNormal];
        }else{
            [self.operationBtn setTitle:@"编辑" forState:UIControlStateNormal];
        }

    }
}
#pragma mark 流转历史
-(void)historyAction{
    OAHistroyViewController* historyVC = (OAHistroyViewController*)[self.storyboard instantiateViewControllerWithIdentifier:@"HistoryVC"];
    historyVC.fileId = self.fileId;
    [self.navigationController pushViewController:historyVC animated:YES];
}

-(void)alertViewShow{
    NSString * setp = self.detailModel.setp;
    if ([self.detailModel.setp isEqualToString:@"承办情况1"]) {
        setp = @"承办情况";
    }
    UIAlertView * alertView = [[UIAlertView alloc]initWithTitle:nil message:setp delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    alertView.alertViewStyle = UIAlertViewStylePlainTextInput;
    [alertView show];

}

#pragma mark 签收
-(void)setupSign{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"unId":self.fileId},@{@"userId":userId}];
    [HttpTools postWithURL:KexchdataURL arrays:array method:KSetSignInMethod success:^(id JSON) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        [self.operationBtn setTitle:@"编辑" forState:UIControlStateNormal];
        [self.view makeToast:@"签收成功"];
        [self operationAction:self.operationBtn];
         [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshOADetailData" object:nil];
    } failure:^(NSError *error) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    }];

    
}


#pragma mark 加载网络数据
-(void)loadData{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"unId":self.fileId},@{@"userId":userId}];
    [HttpTools postWithURL:KexchdataURL arrays:array method:KGetOAOfficeMethod success:^(id JSON) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        self.tableView.hidden = NO;
        self.detailModel = [self getDetailModel:JSON];
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    }];
}

//获取解析得到的数据。
-(OADetailModel *)getDetailModel:(NSString*)dataString;
{
    NSData * data = [dataString dataUsingEncoding:NSUTF8StringEncoding];
    OADetailModel * detailModel = [[OADetailModel alloc]init];
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData: data options:0 error:nil];
    //获取根节点（Users）
    GDataXMLElement *rootElement = [doc rootElement];
    //获取根节点下的节点（User）
    NSArray *rootData= [rootElement elementsForName:@"数据"];
    for (GDataXMLElement *subData in rootData) {
        NSArray * tempArray = [subData elementsForName:@"数据要素"];
        for (GDataXMLElement *data in tempArray) {
            GDataXMLElement *sourceElement = [[data elementsForName:@"来文单位"] objectAtIndex:0];
            NSString *source = [sourceElement stringValue];
            detailModel.source = source;
    
            
            GDataXMLElement *titleElement = [[data elementsForName:@"文件标题"] objectAtIndex:0];
            NSString *title = [titleElement stringValue];
            detailModel.title = title;
    
            
            GDataXMLElement *numberElement = [[data elementsForName:@"来文编号"] objectAtIndex:0];
            NSString *number = [numberElement stringValue];
            detailModel.number = number;
            
            GDataXMLElement *fileIdElement = [[data elementsForName:@"唯一标识"] objectAtIndex:0];
            NSString *fileId = [fileIdElement stringValue];
            detailModel.fileId = fileId;
            
            GDataXMLElement *receiveDateElement = [[data elementsForName:@"收文日期"] objectAtIndex:0];
            NSString *receiveDate = [receiveDateElement stringValue];
            detailModel.receiveDate = receiveDate;
            
            GDataXMLElement *fileTypeElement = [[data elementsForName:@"收文类型"] objectAtIndex:0];
            NSString *fileType = [fileTypeElement stringValue];
            detailModel.fileType = fileType;
           
            
            GDataXMLElement *countElement = [[data elementsForName:@"收文份数"] objectAtIndex:0];
            NSString *count = [countElement stringValue];
            detailModel.count = count;
    
            
            
            GDataXMLElement *urgencyElement = [[data elementsForName:@"紧急程度"] objectAtIndex:0];
            NSString *urgency = [urgencyElement stringValue];
            detailModel.urgency = urgency;
        
            
            GDataXMLElement *publicesElement = [[data elementsForName:@"公开"] objectAtIndex:0];
            NSString *publices = [publicesElement stringValue];
              detailModel.publices = publices;
    
            
            GDataXMLElement *bookerElement = [[data elementsForName:@"登记人"] objectAtIndex:0];
            NSString *booker = [bookerElement stringValue];
              detailModel.booker = booker;
        
            
            GDataXMLElement *receivedSortElement= [[data elementsForName:@"收文分类"] objectAtIndex:0];
            NSString *receivedSort = [receivedSortElement stringValue];
              detailModel.receivedSort = receivedSort;

            
            GDataXMLElement *remarksElement= [[data elementsForName:@"备注"] objectAtIndex:0];
            NSString *remarks = [remarksElement stringValue];
               detailModel.remarks = remarks;

            
            GDataXMLElement *officeDoneElement= [[data elementsForName:@"拟办意见"] objectAtIndex:0];
            NSString *officeDone = [officeDoneElement stringValue];
              detailModel.officeDone = officeDone;
           
            
            
            GDataXMLElement *subjectword= [[data elementsForName:@"办理情况"] objectAtIndex:0];
            NSString *subject = [subjectword stringValue];
             detailModel.condition = subject;
            
            GDataXMLElement * leaderScanElement= [[data elementsForName:@"领导批示"] objectAtIndex:0];
            NSString *leaderScan = [leaderScanElement stringValue];
            detailModel.leaderScan = leaderScan;

            
            GDataXMLElement *sugestElement= [[data elementsForName:@"部门意见"] objectAtIndex:0];
            NSString * sugest = [sugestElement stringValue];
             detailModel.sugest = sugest;
            
            GDataXMLElement *setpElement= [[data elementsForName:@"填写意见环节"] objectAtIndex:0];
            NSString * step = [setpElement stringValue];
            detailModel.setp = step;
           
        }
    }
  
    for (GDataXMLElement * subData in rootData) {
        NSArray * tempArray = [subData elementsForName:@"数据实体"];
        for (GDataXMLElement * element in tempArray) {
            NSArray *array = [element elementsForName:@"附件"];
            for (GDataXMLElement * data in array) {
                OAAttachmentsModel * attachModel = [[OAAttachmentsModel alloc]init];
                GDataXMLElement * nameElement = [[data elementsForName:@"名称"] objectAtIndex:0];
               NSString *  name = [nameElement stringValue];
                attachModel.attachmentsTitle = name;
                
                GDataXMLElement * contentElement = [[data elementsForName:@"内容"] objectAtIndex:0];
                NSString *  content = [contentElement stringValue];
                attachModel.attachmentsURL = content;
                
                [self.attachmentArray addObject:attachModel];
            }
        }
    }
    
    for (GDataXMLElement * subData in rootData) {
        NSArray * tempArray = [subData elementsForName:@"正文实体"];
        for (GDataXMLElement * element in tempArray) {
            NSArray *array = [element elementsForName:@"附件"];
            for (GDataXMLElement * data in array) {
                OAAttachmentsModel * attachModel = [[OAAttachmentsModel alloc]init];
                GDataXMLElement * nameElement = [[data elementsForName:@"名称"] objectAtIndex:0];
                NSString *  name = [nameElement stringValue];
                attachModel.attachmentsTitle = name;
                
                GDataXMLElement * contentElement = [[data elementsForName:@"内容"] objectAtIndex:0];
                NSString *  content = [contentElement stringValue];
                attachModel.attachmentsURL = content;
                
                [self.mainattachmentArray addObject:attachModel];
            }
        }
    }

    return detailModel;
    
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    switch (section) {
        case 0:
            return 15;
            break;
        case 1:
            return self.mainattachmentArray.count;;
        case 2:
            return self.attachmentArray.count;
            break;
        default:
            return 1;
            break;
    }
}

#pragma mark UITbableViewCell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0 || indexPath.section == 1) {
        OADetailCell * cell = [OADetailCell cellWihtTableView:tableView];
        cell.textField.delegate = self;
        cell.detailModel = self.detailModel;
        cell.indexPath = indexPath;
       [cell editStatus:self.isEditoring];
        
         return cell;
    }else{
        if (indexPath.section == 1) {
            static NSString * cellIdentifier = @"cellIdentifier";
            UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
            if (cell == nil) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
            }
            OAAttachmentsModel * model = self.mainattachmentArray[indexPath.row];
            cell.textLabel.text = model.attachmentsTitle;
            cell.textLabel.font = [UIFont systemFontOfSize:14];
            cell.textLabel.numberOfLines = 0;
            cell.textLabel.textColor = [UIColor colorWithRed:85/255.0 green:85/255.0  blue:85/255.0 alpha:1.0];
            return cell;
            
        }else{
            static NSString * cellIdentifier = @"cellId";
            UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
            if (cell == nil) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
            }
            OAAttachmentsModel * model = self.attachmentArray[indexPath.row];
            cell.textLabel.text = model.attachmentsTitle;
            cell.textLabel.font = [UIFont systemFontOfSize:14];
            cell.textLabel.numberOfLines = 0;
            cell.textLabel.textColor = [UIColor colorWithRed:85/255.0 green:85/255.0  blue:85/255.0 alpha:1.0];
            return cell;
            
        }
    }
   
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    CGFloat height = 44;
     CGFloat Margin = 35;
  
    if (indexPath.section ==0) {
        if (indexPath.row ==0) {
            height = [OAToolBox sizebyText:self.detailModel.source font:13 minsWidth:80]+ Margin;
        
        }else if (indexPath.row ==1){
                    height = [OAToolBox sizebyText:self.detailModel.fileType font:13 minsWidth:80]+ Margin;
            
            
        }else if (indexPath.row ==2){ 
            
                height = [OAToolBox sizebyText:self.detailModel.fileId font:13 minsWidth:80]+ Margin;
            
          
        }else if (indexPath.row ==3){
          
                height = [OAToolBox sizebyText:self.detailModel.receivedSort font:13 minsWidth:80]+ Margin;
            
            
        }else if (indexPath.row ==4){
           
                height = [OAToolBox sizebyText:self.detailModel.title font:13 minsWidth:80]+ Margin;
            
            
        }else if (indexPath.row ==5){
            
                height = [OAToolBox sizebyText:self.detailModel.urgency font:13 minsWidth:80]+ Margin;
            
            
        }else if (indexPath.row ==6){
           
                height = [OAToolBox sizebyText:self.detailModel.publices font:13 minsWidth:80]+ Margin;
            
        }else if (indexPath.row ==7){
           
                height = [OAToolBox sizebyText:self.detailModel.count font:13 minsWidth:80]+ Margin;
            
        }else if (indexPath.row ==8){
            
            height = [OAToolBox sizebyText:self.detailModel.booker font:13 minsWidth:80]+ Margin;
            
            
        }else if (indexPath.row ==9){
            
            height = [OAToolBox sizebyText:self.detailModel.receiveDate font:13 minsWidth:80]+ Margin;
            
            
        }else if (indexPath.row ==10){
            
            height = [OAToolBox sizebyText:self.detailModel.remarks font:13 minsWidth:80]+ Margin;
            
            
        }else if (indexPath.row ==11){
            if ([self.detailModel.setp isEqualToString:@"拟办意见"]) {
                Margin += 50;
            }
            height = [OAToolBox sizebyText:self.detailModel.officeDone font:13 minsWidth:80]+ Margin;
        }else if (indexPath.row ==12){
            if ([self.detailModel.setp isEqualToString:@"办理情况"]) {
                Margin += 50;
            }
            height = [OAToolBox sizebyText:self.detailModel.condition font:13 minsWidth:100]+ Margin;
        }else if (indexPath.row ==13){
            if ([self.detailModel.setp isEqualToString:@"领导批示"]) {
                Margin += 50;
            }
            height = [OAToolBox sizebyText:self.detailModel.leaderScan font:13 minsWidth:80]+ Margin;
            
        }else if (indexPath.row ==14){
            if ([self.detailModel.setp isEqualToString:@"部门意见"]) {
                Margin += 50;
            }
            height = [OAToolBox sizebyText:self.detailModel.sugest font:13 minsWidth:80]+ Margin;
            
        }
      

    }else if(indexPath.section == 1){
        OAAttachmentsModel * model = self.mainattachmentArray[indexPath.row];
        height = [OAToolBox sizebyText:model.attachmentsTitle font:13 minsWidth:20]+ Margin;        }
    else if (indexPath.section == 2){
        OAAttachmentsModel * model = self.attachmentArray[indexPath.row];
        height = [OAToolBox sizebyText:model.attachmentsTitle font:13 minsWidth:20]+ Margin;
    }
     return height;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 2) {
        UIView * bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth, 21)];
        UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, KScreenWidth, 21)];
        label.text = @"附件";
        label.font = [UIFont systemFontOfSize:14];
        label.textColor = [UIColor colorWithRed:85/255.0 green:85/255.0  blue:85/255.0 alpha:1.0];
        [bgView addSubview:label];
        if (self.attachmentArray.count) {
            label.hidden = NO;
        }else{
            label.hidden = YES;
        }
        return bgView;
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 2) {
        return 21;
    }
    return 0.001;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 1) { //下载附件 查看附件信息
        OAAttachmentsModel * model = self.mainattachmentArray[indexPath.row];
        [self openFileURL:model.attachmentsURL];
    }else if (indexPath.section == 2){
        
        OAAttachmentsModel * model = self.attachmentArray[indexPath.row];
        [self openFileURL:model.attachmentsURL];
    }
    
}

-(void)openFileURL:(NSString*)url{
    NSString * stringurl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
     self.attacmentURL =  [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:[url lastPathComponent]]; //附件路径
    if ([self isExtistFilePathWithFileName:[[NSURL URLWithString:stringurl] lastPathComponent]]) { //已经存在附件
        QLPreviewController *previewoCntroller = [[QLPreviewController alloc] init] ;
        previewoCntroller.delegate=self;
        previewoCntroller.dataSource=self;
        previewoCntroller.navigationItem.rightBarButtonItem=nil;
        [self.navigationController pushViewController: previewoCntroller animated:YES];
        
    }else{
         MBProgressHUD * hud  =  [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.labelText = @"下载中...";
        NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:stringurl]];
        [self.webView loadRequest:request];
    }

}

#pragma mark PreviewDataSource
//第一个方法是设定一组文档浏览的个数，会影响到在文档预览中的上/下一页。
-(NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)controller {
    return 1;
}
//第二个方法是指定文档预览的文件路径
-(id<QLPreviewItem>)previewController:(QLPreviewController *)controller previewItemAtIndex:(NSInteger)index {
    
    return [NSURL fileURLWithPath:self.attacmentURL];
}

-(BOOL)isExtistFilePathWithFileName:(NSString*)fileName{
    NSString * file = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString * filePath = [file stringByAppendingPathComponent:fileName];
    NSFileManager * fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:filePath] && fileName.length != 0) {
        return YES;
    }else{
        return NO;
    }
    
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    NSURL * requestedURL = [request URL];
    NSData * fileData = [[NSData alloc] initWithContentsOfURL:requestedURL];
     NSString * filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    [fileData writeToFile:[filePath stringByAppendingPathComponent:[requestedURL lastPathComponent]] atomically:YES];
    return YES;
}
- (void)webViewDidStartLoad:(UIWebView *)webView{

   
}
- (void)webViewDidFinishLoad:(UIWebView *)webView{
    [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    QLPreviewController *previewoCntroller = [[QLPreviewController alloc] init] ;
    previewoCntroller.delegate=self;
    previewoCntroller.dataSource=self;
    [self.navigationController pushViewController: previewoCntroller animated:YES];
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{

    [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
}

#pragma mark 签收/编辑
- (IBAction)operationAction:(id)sender {
    UIButton * btn = (UIButton*)sender;
    if (self.isUnDoWork && [btn.currentTitle isEqualToString:@"签收"]) {//从待办工作路径过来 先调用 签收 接口
        [self setupSign]; //签收
    }else{
        if ([btn.currentTitle isEqualToString:@"编辑"]) { //开始编辑
            [btn setTitle:@"取消" forState:UIControlStateNormal];
            self.isEditoring = YES;
            self.saveButton.enabled = YES;
            self.sendButton.enabled = YES;
        }else{
            [btn setTitle:@"编辑" forState:UIControlStateNormal]; //取消编辑
            self.isEditoring = NO;
            self.saveButton.enabled = NO;
            self.sendButton.enabled = NO;
        }
    }
    [self.tableView reloadData];
    
}

#pragma mark 保存
- (IBAction)saveAction:(id)sender {
    if (self.textString.length ==0) {
        self.textString = @"";
    }
    
    if ([self.detailModel.setp isEqualToString:@"办理情况"]) {
        self.detailModel.condition =  self.textString;
    }else if ([self.detailModel.setp isEqualToString:@"拟办意见"]){
        self.detailModel.officeDone =  self.textString;
    }else if ([self.detailModel.setp isEqualToString:@"领导批示"]){
        self.detailModel.leaderScan =  self.textString;
    }else if ([self.detailModel.setp isEqualToString:@"部门意见"]){
        self.detailModel.sugest =  self.textString;
    }
    
    [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
    NSArray * array = nil;
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    if (self.detailModel !=nil) {
        self.body = [NSString stringWithFormat:@"&lt;?xml version=\'1.0\' encoding=\'utf-8\'?&gt;\n"
                     "&lt;交换 xmlns=\'exch.jhsx.gov.cn/data\' xmlns:xsi=\'http://www.w3.org/2001/XMLSchema-instance\'&gt;\n"
                     "&lt;数据&gt;\n"
                     "&lt;数据元素&gt;\n"
                     "&lt;唯一标识&gt; %@ &lt;/唯一标识&gt;\n"
                     "&lt;领导批示 类型='3'&gt; %@ &lt;/领导批示&gt;\n"
                     "&lt;部门意见  类型='3'&gt; %@ &lt;/部门意见&gt;\n"
                     "&lt;拟办意见 类型='3'&gt; %@ &lt;/拟办意见&gt;\n"
                     "&lt;办理情况 类型='3'&gt; %@ &lt;/办理情况&gt;\n"
                     "&lt;来文单位 类型='2'&gt; %@ &lt;/来文单位&gt;\n"
                     "&lt;文件标题 类型='2'&gt; %@ &lt;/文件标题&gt;\n"
                     "&lt;来文编号 类型='2'&gt; %@&lt;/来文编号&gt;\n"
                     "&lt;收文日期 类型='2'&gt; %@ &lt;/收文日期&gt;\n"
                     "&lt;收文类型  类型='2'&gt; %@ &lt;/收文类型&gt;\n"
                     "&lt;收文份数  类型='2'&gt; %@ &lt;/收文份数&gt;\n"
                     "&lt;紧急程度  类型='2'&gt; %@ &lt;/紧急程度&gt;\n"
                     "&lt;公开  类型='2'&gt; %@ &lt;/公开&gt;\n"
                     "&lt;收文分类  类型='2'&gt; %@ &lt;/收文分类&gt;\n"
                     "&lt;登记人 类型='2'&gt; %@ &lt;/登记人&gt;\n"
                     "&lt;备注 类型='2'&gt; %@ &lt;/备注&gt;\n"
                     "&lt;/数据元素&gt;\n"
                     "&lt;数据实体&gt;\n"
                     "&lt;附件&gt;\n"
                     "%@"
                     "&lt;/附件&gt;\n"
                     "&lt;/数据实体&gt;\n"
                     "&lt;/数据&gt;\n"
                     "&lt;/交换&gt;",
                     self.detailModel.fileId,
                     self.detailModel.leaderScan,
                     self.detailModel.sugest,
                     self.detailModel.officeDone,
                     self.detailModel.condition,
                     self.detailModel.source,
                     self.detailModel.title,
                     self.detailModel.number,
                     self.detailModel.receiveDate,
                     self.detailModel.fileType,
                     self.detailModel.count,
                     self.detailModel.urgency,
                     self.detailModel.publices,
                     self.detailModel.receivedSort,
                     self.detailModel.booker,
                     self.detailModel.remarks,
                     [self returnString]];
        array = @[@{@"unid":self.detailModel.fileId},@{@"userId":userId},@{@"famxml":self.body}];
        
    }
    
    [HttpTools postWithURL:KexchdataURL arrays:array method:KSetSaveWork success:^(id JSON) {
        [MBProgressHUD hideAllHUDsForView:self.navigationController.view animated:YES];
        [self.view makeToast:@"保存成功"];
         [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshOADetailData" object:nil];
        
    } failure:^(NSError *error) {
          [MBProgressHUD hideAllHUDsForView:self.navigationController.view animated:YES];
    }];
}

-(NSString *)returnString
{
    NSString *string = [[NSString alloc]init];
    string = @"&lt;名称&gt;%@&lt;/名称&gt;\n"
    "&lt;内容&gt;%@&lt;/内容&gt;\n";
    
    NSMutableString *str = [NSMutableString string];
    for (int i = 0; i<self.attachmentArray.count; i++) {
        OAAttachmentsModel * attachModel = self.attachmentArray[i];
        [str appendString: [NSString stringWithFormat:string,attachModel.attachmentsTitle,attachModel.attachmentsURL]];
    }
    
    return str;
}
#pragma mark 发送
- (IBAction)cilcuationAction:(id)sender {
    if (self.detailModel.setp.length !=0) {
        if (self.textString.length == 0 && self.isEditoring) {
            [self.view makeToast:@"请填写意见"];
            return;
        }
    }
    
    [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
    NSArray * array = nil;
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    if (self.detailModel !=nil) {
      self.body = [NSString stringWithFormat:@"&lt;?xml version=\'1.0\' encoding=\'utf-8\'?&gt;\n"
                     "&lt;交换 xmlns=\'exch.jhsx.gov.cn/data\' xmlns:xsi=\'http://www.w3.org/2001/XMLSchema-instance\'&gt;\n"
                     "&lt;数据&gt;\n"
                     "&lt;数据元素&gt;\n"
                     "&lt;唯一标识&gt; %@ &lt;/唯一标识&gt;\n"
                     "&lt;领导批示 类型='3'&gt; %@ &lt;/领导批示&gt;\n"
                     "&lt;部门意见  类型='3'&gt; %@ &lt;/部门意见&gt;\n"
                     "&lt;拟办意见 类型='3'&gt; %@ &lt;/拟办意见&gt;\n"
                     "&lt;办理情况 类型='3'&gt; %@ &lt;/办理情况&gt;\n"
                     "&lt;来文单位 类型='2'&gt; %@ &lt;/来文单位&gt;\n"
                     "&lt;文件标题 类型='2'&gt; %@ &lt;/文件标题&gt;\n"
                     "&lt;来文编号 类型='2'&gt; %@&lt;/来文编号&gt;\n"
                     "&lt;收文日期 类型='2'&gt; %@ &lt;/收文日期&gt;\n"
                     "&lt;收文类型  类型='2'&gt; %@ &lt;/收文类型&gt;\n"
                     "&lt;收文份数  类型='2'&gt; %@ &lt;/收文份数&gt;\n"
                     "&lt;紧急程度  类型='2'&gt; %@ &lt;/紧急程度&gt;\n"
                     "&lt;公开  类型='2'&gt; %@ &lt;/公开&gt;\n"
                     "&lt;收文分类  类型='2'&gt; %@ &lt;/收文分类&gt;\n"
                     "&lt;登记人 类型='2'&gt; %@ &lt;/登记人&gt;\n"
                     "&lt;备注 类型='2'&gt; %@ &lt;/备注&gt;\n"
                     "&lt;/数据元素&gt;\n"
                     "&lt;数据实体&gt;\n"
                     "&lt;附件&gt;\n"
                     "%@"
                     "&lt;/附件&gt;\n"
                     "&lt;/数据实体&gt;\n"
                     "&lt;/数据&gt;\n"
                     "&lt;/交换&gt;",
                    self.detailModel.fileId,
                   self.detailModel.leaderScan,
                   self.detailModel.sugest,
                   self.detailModel.officeDone,
                   self.detailModel.condition,
                   self.detailModel.source,
                   self.detailModel.title,
                   self.detailModel.number,
                   self.detailModel.receiveDate,
                   self.detailModel.fileType,
                   self.detailModel.count,
                   self.detailModel.urgency,
                   self.detailModel.publices,
                   self.detailModel.receivedSort,
                   self.detailModel.booker,
                   self.detailModel.remarks,
                   [self returnString]];
        array = @[@{@"unid":self.detailModel.fileId},@{@"userId":userId},@{@"famxml":self.body}];
        
    }
    
    
    [HttpTools postWithURL:KexchdataURL arrays:array method:KSetSubmitWorkMethod success:^(id JSON) {
        [MBProgressHUD hideAllHUDsForView:self.navigationController.view animated:YES];
        self.departments = [self dataWith:JSON];
        if ([self.infoString isEqualToString:@"1044"]) {
            [self.view makeToast:@"1044"];
        }
        if ([self.infoString isEqualToString:@"11"]) { //成功发送，提交下一办理人
            
            [UIAlertView showWithTitle:@"提示" message:@"发送成功" cancelButtonTitle:@"确定" otherButtonTitles:nil tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
                
                [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshOADetailData" object:nil];
                [self.navigationController popToViewController:self.navigationController.viewControllers[1] animated:YES];
            }];
            
        }else if ([self.infoString isEqualToString:@"12"]) { //返回环节信息
            OASelectDepartmentController * selectVC = [[OASelectDepartmentController alloc]init];
             selectVC.subItems = self.subItems;
            selectVC.body = self.body;
            selectVC.fileId = self.self.detailModel.fileId;
            selectVC.attachmentArray = self.attachmentArray;
            selectVC.departments = self.departments;
            [self.navigationController pushViewController:selectVC animated:YES];
        }else if ([self.infoString isEqualToString:@"13"]) {//返回人员列表
//            OASelectPersonController * selectPersonVC = [[OASelectPersonController alloc]init];
//            selectPersonVC.personArray = self.personArray;
//            selectPersonVC.body = self.body;
//            selectPersonVC.setpString = self.setpString;
//            if (self.detailModel ) {
//                selectPersonVC.fileId = self.detailModel.fileId;
//            }else if (self.detailPatchModel){
//                selectPersonVC.fileId = self.detailPatchModel.fileId;
//            }
//            
//            [self.navigationController pushViewController:selectPersonVC animated:YES];
        
        }else if ([self.infoString isEqualToString:@"14"]){ //返回树
//            OASelectPersonSecondController * selectPersonVC = [[OASelectPersonSecondController alloc]init];
//            selectPersonVC.personArray = self.personArray;
//            selectPersonVC.body = self.body;
//            selectPersonVC.setpString = self.setpString;
//            if (self.detailModel ) {
//                selectPersonVC.fileId = self.detailModel.fileId;
//            }else if (self.detailPatchModel){
//                selectPersonVC.fileId = self.detailPatchModel.fileId;
//            }
//            selectPersonVC.groupArray = self.groupArray;
//            selectPersonVC.rowArray = self.rowArray;
//            [self.navigationController pushViewController:selectPersonVC animated:YES];
            
        }
    } failure:^(NSError *error) {
        [MBProgressHUD hideAllHUDsForView:self.navigationController.view animated:YES];
    }];
    
}

#pragma mark 数据解析

-(NSMutableArray*)dataWith:(NSString*)dataString
{
    NSData * data = [dataString dataUsingEncoding:NSUTF8StringEncoding];
    NSMutableArray *arrData = [[NSMutableArray alloc]init];
     NSMutableArray * subData = [NSMutableArray array];
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData: data options:0 error:nil];
    GDataXMLElement *rootElement = [doc rootElement];
    NSArray *users = [rootElement children];
    for (int i = 0;i<[users count];i++) {
        GDataXMLElement *ele = [users objectAtIndex:i];
        if ([[ele name] isEqualToString:@"环节"]){
            OADepartmentModel * model = [[OADepartmentModel alloc]init];
            model.department = [[ele attributeForName:@"流向"] stringValue];
            for (int j=0; j<[ele childCount]; j++) {
                GDataXMLElement  *subItem = [ele childAtIndex:j];
                [subData addObject:subItem.stringValue];
            
            }
            [arrData addObject:model];
        }
    }
    self.subItems = subData; //选中 需要提交得数据
    NSArray *infoData= [rootElement elementsForName:@"info"];
    for (int i = 0;i<[infoData count];i++)
    {
        GDataXMLElement *infoElement = [infoData objectAtIndex:i];
        self.infoString = [infoElement stringValue];
    }
    
    return arrData;
}

- (void)textFieldDidEndEditing:(UITextField *)textField{
        self.textString = textField.text;
        OADetailModel * model = [[OADetailModel alloc]init];
        if ([self.detailModel.setp isEqualToString:@"办理情况"]) {
            model.condition = textField.text;
            self.detailModel.condition =[NSString stringWithFormat:@"%@(iOS%@)",model.condition,KSystemVersion] ;
        }else if ([self.detailModel.setp isEqualToString:@"拟办意见"]){
            model.officeDone = textField.text;
            self.detailModel.officeDone = [NSString stringWithFormat:@"%@(iOS%@)",model.officeDone,KSystemVersion] ;
        }else if ([self.detailModel.setp isEqualToString:@"领导批示"]){
            model.leaderScan = textField.text;
            self.detailModel.leaderScan = [NSString stringWithFormat:@"%@(iOS%@)",model.leaderScan,KSystemVersion];
        }else if ([self.detailModel.setp isEqualToString:@"部门意见"]){
            model.sugest = textField.text;
            self.detailModel.sugest = [NSString stringWithFormat:@"%@(iOS%@)",model.sugest,KSystemVersion];
        }
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
